<?php


namespace common\helpers;
use Yii;
use Lcobucci\JWT\ValidationData;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;

class JwtApi
{
    private static $_config = [
        'audience' => 'http://www.pyg.com',//接收人
        'id' => 'hdskjffdsdsf',//token的唯一标识，这里只是一个简单示例
        'sign' => '9uejwqekndkjsafndsidskjfkjdsf',//签名密钥
        'issuer' => 'http://adasdsaminapi.pyg.com',//签发人
        'expire' => 3600*24,
        'mark' => 'mark',
    ];
    public function __construct($id,$expire=86400)
    {
        self::$_config['id'] = $id;
        self::$_config['expire'] = $expire;
    }

    /**
     * 生成token
     * @param $user_id 标识
     * @return string
     */
    public function getToken($mark){
        //签名对象
        $signer = new Sha256();
        //获取当前时间戳
        $time = time();
        //设置签发人、接收人、唯一标识、签发时间、立即生效、过期时间、用户id、签名
        $token = (new Builder())->issuedBy(self::$_config['issuer'])
            ->canOnlyBeUsedBy(self::$_config['audience'])
            ->identifiedBy(self::$_config['id'], true)
            ->issuedAt($time)
            ->canOnlyBeUsedAfter($time-1)
            ->expiresAt($time + self::$_config['expire'])
            ->withClaim(self::$_config['mark'], $mark)
            ->sign($signer, self::$_config['sign'])
            ->getToken();
        return (string)$token;
    }

    /**
     * 从token中获取用户id （包含token的校验）
     * @param null $token
     * @return mixed|null
     */
    public function getUserId($token = null)
    {
        $user_id = null;
        try {
            if (!empty($token)) {
                $token = (new Parser())->parse((string) $token);
                //验证token
                $data = new ValidationData();
                $data->setIssuer(self::$_config['issuer']);//验证的签发人
                $data->setAudience(self::$_config['audience']);//验证的接收人
                $data->setId(self::$_config['id']);//验证token标识
                if (!$token->validate($data)) {
                    return $user_id;
                }
                //验证签名
                $signer = new Sha256();
                if (!$token->verify($signer, self::$_config['sign'])) {
                    return $user_id;
                }
                $user_id = $token->getClaim(self::$_config['mark']);
            }
        }catch (\Exception $e){

        }catch (\Error $error){

        }
        return $user_id;
    }

    /**
     * 从请求信息中获取token令牌
     * @return false|string
     */
    public function getRequestToken()
    {
        if (empty($_SERVER['HTTP_TOKEN'])) {
            return false;
        }
        $header = $_SERVER['HTTP_TOKEN'];
        $method = 'bearer';
        //去除token中可能存在的bearer标识
        return trim(str_ireplace($method, '', $header));
    }
}